package com.yly.test1.utils;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;

public class ToastUtils {

    private static Toast sToast;
    private static Handler sMainHandler;

    private ToastUtils() {
        throw new UnsupportedOperationException("it is a utils class, should not be newInstance");
    }

    public static void show(Context ctx, String content) {

        //判断当前是否在UI线程
        if (Looper.myLooper() != Looper.getMainLooper()) {
            if (sMainHandler == null) {
                sMainHandler = new Handler(Looper.getMainLooper());
            }

            sMainHandler.post(() -> showInner(ctx, content));
        } else {

            showInner(ctx, content);
        }

    }

    private static void showInner(Context ctx, String content) {
        //避免频繁创建Toast对象，也能防止Toast风暴
        if (sToast == null) {
            sToast = Toast.makeText(ctx, content, Toast.LENGTH_SHORT);
        } else {
            sToast.setText(content);
        }
        sToast.show();
    }

}
